package com.voicechat.firstmet.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PhotoAlbumBean;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.LabelsView;
import com.voicechat.firstmet.view.LazyViewPager;
import com.voicechat.firstmet.view.SimpleViewPagerIndicatorLook;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: SearchActivity
 * @Description: 搜索用户和帖子页面
 * @Author: ljp
 * @CreateDate: 2018/10/15 9:52
 * @Version: 1.0
 */
public class SearchActivity extends BaseActivity {
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.largeLabe_history)
    LabelsView largeLabeHistory;
    @BindView(R.id.largeLabe_hot)
    LabelsView largeLabeHot;
    @BindView(R.id.linear_history)
    LinearLayout linearHistory;
    @BindView(R.id.linear_hot)
    LinearLayout linearHot;
    @BindView(R.id.linear_search)
    LinearLayout linearSearch;
    @BindView(R.id.indicator_search)
    SimpleViewPagerIndicatorLook indicatorSearch;
    @BindView(R.id.linear_search_fragment)
    LinearLayout linearSearchFragment;
    @BindView(R.id.viewpager_search)
    LazyViewPager viewpagerSearch;
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    List<String> listDataHistory;
    private String token;
    private String deviceInfo;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String userId;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_search;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        userId = mySeleInfo.getId();
        initHot();
        initView();
    }
    /**
    * @method
    * @description 热门搜索请求
    * @date: 2018/11/16 10:38
    * @author: ljp
    * @return
    */
    private void initHot() {
        MeInfoService.hotSearch(userId,token,deviceInfo).subscribe(photoAlbumBean -> {
           // Log.i("initHot", "initHot: -----"+photoAlbumBean.getList().size());
            if(photoAlbumBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                if(photoAlbumBean.getList() != null) {
                    largeLabeHot.setLabels(photoAlbumBean.getList(), new LabelsView.LabelTextProvider<PhotoAlbumBean.ListBean>() {
                        @Override
                        public CharSequence getLabelText(TextView label, int position, PhotoAlbumBean.ListBean data) {
                            return data.getName();
                        }
                    });
                }
            }else if(photoAlbumBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            }else {
                toast_MakeText(photoAlbumBean.getMsg());
            }
        },throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
            //Log.i(TAG, "initHot: -----"+throwable.toString());
        });

    }
    /**
    * @method
    * @description 数据控件实例化
    * @date: 2018/11/16 10:38
    * @author: ljp
    * @return
    */
    private void initView() {
        listDataHistory = SPUtils.getListData(SPUtils.SP_SEARCH, String.class);
        if (listDataHistory == null || listDataHistory.size() == 0){
            linearHistory.setVisibility(View.GONE);
        }else {
            largeLabeHistory.setLabels(listDataHistory);
        }
        //largeLabeHot.setLabels(listDataHistory);

        etSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //发现执行了两次因为onkey事件包含了down和up事件，所以只需要加入其中一个即可。
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(activity.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
                return false;
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if(!TextUtils.isEmpty(etSearch.getText().toString().trim())){
                        /*tvCancel.setVisibility(View.GONE);
                        linearBack.setVisibility(View.VISIBLE);
                        linearSearchFragment.setVisibility(View.VISIBLE);
                        linearSearch.setVisibility(View.GONE);*/
                        setSearchTitle(etSearch.getText().toString().trim());//保存历史数据到本地
                        if(!TextUtils.isEmpty(etSearch.getText().toString().trim())){
                            Intent intent = new Intent(activity,SearchShowActivity.class);
                            intent.putExtra("search",etSearch.getText().toString().trim());
                            startActivity(intent);
                            //finish();
                        }
                    }
                    return true;
                }
                return false;
            }
        });
        largeLabeHistory.setOnLabelClickListener(new LabelsView.OnLabelClickListener() {
            @Override
            public void onLabelClick(TextView label, Object data, int position) {
                String string = data.toString();
                etSearch.setText(string);
                etSearch.setSelection(string.length());
                setSearchTitle(string);
                Intent intent = new Intent(activity,SearchShowActivity.class);
                intent.putExtra("search",string);
                startActivity(intent);
                //finish();
            }
        });
        largeLabeHot.setOnLabelClickListener(new LabelsView.OnLabelClickListener() {
            @Override
            public void onLabelClick(TextView label, Object data, int position) {
                PhotoAlbumBean.ListBean listBean = (PhotoAlbumBean.ListBean) data;
                etSearch.setText(listBean.getName());
                etSearch.setSelection(listBean.getName().length());
                setSearchTitle(listBean.getName());
                Intent intent = new Intent(activity,SearchShowActivity.class);
                intent.putExtra("search",listBean.getName());
                startActivity(intent);
               // finish();
            }
        });

    }
    /**
    * @method
    * @description 保存历史数据到本地
    * @date: 2018/11/16 10:26
    * @author: ljp
    * @return
    */
    public void setSearchTitle(String title) {
        List<String> strings = new ArrayList<>();
        if(listDataHistory.size() >  9){//判断历史数据是否已经是10条
            listDataHistory.remove(listDataHistory.size()-1);//如果是，删除最后一条，添加最新的一条
        }
        String trim = title;
        if(title.length() > 10){
            trim = title.substring(0,10);
        }
        if(listDataHistory.contains(trim)){//判断历史搜索是否包含目前搜索的数据，如果有  覆盖
            listDataHistory.remove(trim);
        }
        strings.add(trim);
        strings.addAll(listDataHistory);
        SPUtils.putListData(SPUtils.SP_SEARCH,strings);
    }


    @OnClick({R.id.linear_back, R.id.tv_cancel})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                /*tvCancel.setVisibility(View.VISIBLE);
                linearBack.setVisibility(View.GONE);
                linearSearchFragment.setVisibility(View.GONE);
                linearSearch.setVisibility(View.VISIBLE);*/
                break;
            case R.id.tv_cancel:
                finish();
                break;
        }
    }

}
